﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure.Data;
using Keepo.Models;
using Keepo.Helpers;
using AlbumDesigner.Models.Enums;
using AlbumDesigner.Helpers;

namespace AlbumDesigner.Controllers
{
    [CheckPermission(section = "ApprovalChecks")]
    public class ApprovalChecksController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetApprovalCheckList()
        {
            using (GenericRepository repository = new GenericRepository())
            {
                var checks = repository.GetAll<ApprovalCheck>().ToList();

                return Json(checks);
            }
        }

        public ActionResult Update(ApprovalCheck check)
        {
            using (GenericRepository repository = new GenericRepository())
            {
                var existingCheck = repository.GetByKey<ApprovalCheck>(check.ApprovalCheckId);

                //the approval check exists in DB
                if (existingCheck != null)
                {
                    //update the relevant fields
                    existingCheck.Title = check.Title;
                    existingCheck.IsSection = check.IsSection;

                    repository.UnitOfWork.SaveChanges();

                    return Json(existingCheck.ApprovalCheckId);
                }
                //the approval check is new
                else
                {
                    var approvalCheck = new ApprovalCheck();
                    approvalCheck.Title = check.Title;
                    approvalCheck.IsSection = check.IsSection;

                    //insert this new Approval Check
                    repository.Add<ApprovalCheck>(approvalCheck);

                    repository.UnitOfWork.SaveChanges();

                    return Json(approvalCheck.ApprovalCheckId);
                }
            }
        }

        public ActionResult Delete(int id)
        {
            using (GenericRepository repository = new GenericRepository())
            {
                //delete the specified ApprovalCheck
                repository.Delete<ApprovalCheck>(m => m.ApprovalCheckId == id);

                repository.UnitOfWork.SaveChanges();

                return Json(new KeyValuePair<bool, string>(true, "השאלה נמחקה בהצלחה"));
            }
        }
    }
}
